import express from "express";
import db from "./../libs/DBhelper";
import md5 from "md5";
import fs from "fs";
import path from "path";

let apiRouter = express.Router();

//注册模块
apiRouter.post("/reg", (request, response, next) => {
    //把路径,用户名,密码..保存到数据库
    //准备sql语句
    let sql = "INSERT INTO `users` (`u_phone`,`u_pwd`) VALUES(?,?);";
    //准备参数
    let params = [
        request.body.u_phone,
        md5(md5(request.body.u_pwd) + require("./../libs/Configs").keys), //使用MD5加密
    ]

    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: err.message,
                status: -2,
                
            });
            return;
        }
        if (result.affectedRows >= 1) {
            response.json({
                msg: "注册成功",
                status: 1
            })
        } else {
            response.json({
                msg: "注册失败",
                status: -1
            });
        }
    })
})

//登录模块
apiRouter.post("/login", (request, response, next) => {

    let sql = "SELECT `u_id`,`u_phone` FROM users WHERE  u_status=1 AND u_phone=? AND u_pwd=?;";
    let params = [
        request.body.u_phone,
        md5(md5(request.body.u_pwd) + require("./../libs/Configs").keys), //md5 2次加密
    ]
    
    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: "登录失败",
                err: err.message,
                status:-2
            })
            return;
        }

        if (result.length >= 1) {
            request.session["users"]="jiagenb"
            response.json({
                msg: "登录成功",
                status: 1,
                data:result[0]
            })
        } else {
            response.json({
                msg: "登录失败,用户名或密码错误",
                status: -1
            })
        }
    })
})

//退出登录
apiRouter.get("/quit", (request, response, next) => {
    if (request.session["users"]) {
        request.session["users"] = null;
    }
    response.json({
        msg: "退出成功",
        status: 1
    })
    //前端 把 localStorage里头的数据清除

})

//产品列表
apiRouter.get("/details", (request, response, next) => {
    var detailsStr = fs.readFileSync("./data/list.json", {
        encoding: "utf-8"
    }).toString();
    response.end(detailsStr);
})
//产品列表
apiRouter.get("/detailsinfo/:id", (request, response, next) => {
    var detailsStr = fs.readFileSync("./data/list.json", {
        encoding: "utf-8"
    }).toString();

    var resultObj = JSON.parse(detailsStr).filter((el) => {
        return el.p_id == request.params.id
    })
    response.json(resultObj);
})


//加入购物车接口
apiRouter.post("/addcart", (request, response, next) => {
    //异常捕获
    try {
        //1.更加用户名和商品id 查询 该数据是否存在
        let querySelect = "SELECT * FROM `carts` WHERE  u_id=? AND p_id=?;";
        let queryPrams = [
            request.body.u_id,
            request.body.p_id
        ]
        db.exec(querySelect, queryPrams, (err, queryResult) => {
            //查询返回结果,结果是一个数组 length属性
            if (queryResult.length >= 1) {
                var updateSql = "UPDATE carts SET p_number=p_number+? , p_total=p_number*p_price WHERE u_id=? AND p_id=? ;";
                let updatePrams = [
                    request.body.p_number,
                    request.body.u_id,
                    request.body.p_id
                ]
                db.exec(updateSql, updatePrams, (err, updateReulst) => {

                    if (updateReulst.affectedRows == 1) {
                        response.json({
                            msg: "加入购物成功",
                            status: 1
                        })
                    } else {
                        response.json({
                            msg: "加入购物车失败",
                            status: -1
                        })
                    }
                });

            } else {
                // 加入到数据库,需要准备的参数?
                // 商品id,用户名id,商品名称,商品价格,商品数量,商品图片 ,商品描述
                let sql = "INSERT INTO carts (u_id ,p_id, p_name , p_price , p_number , p_img ,p_total)VALUES(?,?,?,?,?,?,?);";
                let params = [
                    request.body.u_id,
                    request.body.p_id,
                    request.body.p_name,
                    request.body.p_price,
                    request.body.p_number,
                    request.body.p_mid_img,
                    request.body.p_price * request.body.p_number
                ]
                
                db.exec(sql, params, (err, result) => {
                    if (err) {
                        console.log(err.message)
                        response.json({
                            msg: "加入购物车失败",
                            status: -1,
                            err: err.message
                        })
                    }
                    if (result.affectedRows >= 1) {
                        response.json({
                            msg: "加入购物成功",
                            status: 1
                        })
                    }
                })
            }
        });
    } catch (err) {
        response.json({
            msg: "加入购物车失败",
            err: err.message,
            status: -2
        })
    }
})

//获取购物车的数据
apiRouter.get("/getcart", (request, response, next) => {
    let sql = " SELECT * FROM `carts` WHERE  u_id=? ;";
    let params = [
        request.query.u_id
    ]
    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: "加载购物车列表失败",
                status: -2,
                err: err.message
            });
            return;
        }
        response.json({
            msg: "加载成功",
            status: 1,
            data: result
        });
    })
})
//按钮控制加加减减并返回到后台
apiRouter.post("/modify", (request, response, next) => {
    var updateSql = "UPDATE carts SET p_number=?, p_total=p_number*p_price WHERE c_id=? ;";
    let updatePrams = [
        request.body.num,
        request.body.c_id,
    ]

    db.exec(updateSql, updatePrams, (err, updateReulst) => {
        if (err) {
            response.json({
                msg: "加入购物车失败",
                status: -1,
                err: err.message
            })

            return;
        }
        if (updateReulst.affectedRows == 1) {
            response.json({
                msg: "加入购物成功",
                status: 1
            })
        }
    });
})

//删除购物车
apiRouter.post("/delete", async (request, response, next) => {
    let sql = "DELETE FROM carts WHERE  c_id=? ;";
    let params = [request.body.c_id];
    let result = await db.execAsync(sql, params).catch((err) => {
        response.json({
            msg: "删除失败",
            err: err.message
        })
    })
    if (result.affectedRows >= 1) {
        response.json({
            msg: "删除成功",
            status: 1
        })
    } else {
        response.json({
            msg: "删除失败"
        })
    }
})

//清空购物车
apiRouter.post("/deleteAll",(request, response, next) => {
    let sql = "DELETE FROM carts WHERE  u_id=? ;";
    let params = [request.body.u_id];

    db.exec(sql,params,(err,res)=>{
        if(err){
            response.json({
                msg:"清空购物车失败",
                status:-1,
                err:err.message
            })
            return
        }
        if(res.affectedRows>=1){
            response.json({
                msg:"清空购物车成功",
                status:1
            })
        }
    })
    // try {
    //     let result = await db.execAsync(sql, params);
    
    //     if (result.affectedRows >= 1) {
    //         response.json({
    //             msg: "清空成功",
    //             status: 1
    //         })
    //     } else {
    //         response.json({
    //             msg: "清空失败"
    //         })
    //     }
    // } catch (err) {
    //     response.json({
    //         msg: "清空购物车失败",
    //         err: err.message
    //     })
    // }
})

//暴露保安大爷(路由对象)
module.exports={
    apiRouter
}